package com.bzg.manager.controller.utils;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.bzg.manager.bean.Auth;
import com.bzg.manager.dao.UserMapper;
import com.bzg.manager.utils.MD5;

/**
 * @Title: VerifiUtil.java
 * @Description: 前后台校验秘钥的工具类 
 * @author guomaoyang
 * @date 2017-1-13 上午9:43:58
 */
@Component
public class VerifiUtil {
	
	public final static  String key = "912920b4c88420a3af455853fff67d74";
	
	@Autowired
	private UserMapper userMapper;
	
	private static VerifiUtil verifiUtil;
	
	
	
	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	//静态工具类注入service写法！
	@PostConstruct  
    public void init() {  
		verifiUtil = this;  
		verifiUtil.userMapper = this.userMapper;  
    }  
	
	
	/**
	 * @Title: baseVerifity
	 * @Description:校验直接调用的方法
	 * @param json 
	 * @return boolean
	 */
	public static boolean baseVerifity(JSONObject json){
		Auth auth = JSONObject.toJavaObject(json.getJSONObject("auth"), Auth.class);
		String info = json.getString("info");
		
		return verifity(auth, info);
	}
	
	public static boolean verifity(Auth auth ,String info){
		if(auth == null){
			return false;
		}
		//判断用户登录情况
		if("-1".equals(auth.getUid())){ // "-1" 表示用户未登录
			//未登录情况只需要验证key
			String server_key = MD5.md5(key);
			if(server_key.equals(auth.getApp_key())){
				return true;
			}
			return false;
		}
		
		return verifityLogined(auth, info);
	}
	
	/**
	 * @Title: verifityLogined
	 * @Description:用户已登录的校验方式
	 * @param auth
	 * @param info
	 * @return boolean
	 */
	public static boolean verifityLogined(Auth auth,String info){
		//生成自己的app_key，根据用户名查询密码
		String uid = auth.getUid();
		String password = verifiUtil.userMapper.getPassword(uid);
		if(StringUtils.isEmpty(password)){
			return false;
		}
		String app_key = MD5.md5(key + MD5.md5(password));
		String server_CRC = MD5.md5(auth.getTime_stamp() + auth.getImei() + app_key + info + auth.getUid());
		if (server_CRC.equals(auth.getCrc())) {
			return true;
		}
		return false;
	}
}
